package cn.passlink.bletoothchat.mActivity;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.passlink.bletoothchat.Entity.Groups;
import cn.passlink.bletoothchat.Entity.mUser;
import cn.passlink.bletoothchat.Entity.singleGroup;
import cn.passlink.bletoothchat.R;
import cn.passlink.bletoothchat.SqlTables.FriendsTableManager;
import cn.passlink.bletoothchat.SqlTables.GroupsTableManager;
import cn.passlink.bletoothchat.SqlTables.MyDatabaseHelper;
import cn.passlink.bletoothchat.SqlTables.UserTableManager;
import cn.passlink.bletoothchat.SqlTables.singleGroupTableManager;
import cn.passlink.bletoothchat.Tools.UserId.GroupIDGenerator;

public class CreateGroupActivity extends AppCompatActivity {
    private Groups mGroups= new Groups();
    private mUser user=new mUser();
    private SQLiteDatabase database;
    private MyDatabaseHelper databaseHelper;
    private Context mContext=this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);
        ImageView backButton=(ImageView) findViewById(R.id.create_group_back_button);
        ImageView createButton=(ImageView) findViewById(R.id.create_group_imageView);
        TextView  crete_text=(TextView) findViewById(R.id.create_group_editText);


        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToTargetActivity();
            }
        });

        createButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 初始化 databaseHelper
                databaseHelper = new MyDatabaseHelper(mContext, 2);
                database=databaseHelper.getWritableDatabase();
                UserTableManager mUserTableManager=new UserTableManager(database);
                user=mUserTableManager.getUserByPhone("1");
                GroupsTableManager mGroupsTableManager=new GroupsTableManager(database);
                //构造数据
                mGroups.setGroupname( crete_text.getText().toString());
                mGroups.setGroup_table_name(GroupIDGenerator.convertToUniqueString(mGroups.getGroupname()));
                mGroups.setMembers_amount("1");
                String groupId = GroupIDGenerator.generateGroupID(mGroups.getGroupname(), user.getPhone());
                mGroups.setGroupid(groupId);

                // 检查表是否存在
                boolean isTableExists = checkTableExists(database, mGroups.getGroup_table_name());
                // 根据结果处理逻辑
                if (isTableExists) {
                    // 表存在
                    Toast.makeText(mContext, mGroups.getGroupname()+"已经存在", Toast.LENGTH_SHORT).show();
                } else {
                    // 表不存在
                   try {
                       // 创建新表的SQL语句
                       mGroupsTableManager.addGroup(mGroups);
                       String createTableQuery = "CREATE TABLE `" +mGroups.getGroup_table_name() + "` (" +
                               "`id` INTEGER PRIMARY KEY AUTOINCREMENT," +
                               "`member_name` TEXT DEFAULT NULL," +
                               "`member_phone` TEXT DEFAULT NULL" +
                               ")";

                       // 执行创建表的SQL语句
                       database.execSQL(createTableQuery);

                       singleGroupTableManager singleGroupTableManager=new singleGroupTableManager(database,mGroups.getGroup_table_name());
                       singleGroup singleGroup=new singleGroup(user.getUsername(),user.getPhone());

                       singleGroupTableManager.addMember(singleGroup);

                       Toast.makeText(mContext, mGroups.getGroupname()+"添加成功！！！", Toast.LENGTH_SHORT).show();
                   }catch (Exception e){
                       Toast.makeText(mContext, mGroups.getGroupname()+"添加失败！请重试", Toast.LENGTH_SHORT).show();
                   }


                }
            }
        });

    }



    public void goToTargetActivity() {
        Intent intent = new Intent(this, RelationshipActivity.class);
//        intent.putExtra("key", "value");
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(database!=null){
            database.close();
        }
    }
    public boolean checkTableExists(SQLiteDatabase database, String tableName) {
        // 执行查询语句检查表是否存在
        String checkTableQuery = "SELECT name FROM sqlite_master WHERE type='table' AND name='" + tableName + "'";
        Cursor cursor = database.rawQuery(checkTableQuery, null);

        // 检查结果集是否包含数据行
        boolean tableExists = cursor.moveToFirst();

        // 关闭游标
        cursor.close();

        // 返回结果
        return tableExists;
    }
}